const query = require('../utils/DB')
class accessModel {
    // 获取权限列表
    // static allList = []
    static async getAccessList(pid = 0) {
        let allList = []
        let list = await query(`select *,name as label,aid as value from access where pid=${pid}`)
        if (list.length > 0) {
            let temp = []
            for (let i = 0; i < list.length; i++) {
                // if(list[i].menutype===2){
                //     temp.push(list[i].val)
                //     allList.push({promission:temp})
                // }else{
                allList.push({ ...list[i], children: await accessModel.getAccessList(list[i].aid) })
                // }
            }
        } else {
            return []
        }
        return allList

    }

    static async addAccess(name, path, pid, redirect, component, menutype, val, keepalive) {
        return query(`INSERT INTO access(name, path, pid, redirect, component, menutype, val, keepalive) VALUES ('${name}', '${path??""}', ${pid??0}, '${redirect??""}', '${component??""}', ${menutype}, '${val??""}', ${keepalive??2})`)
    }

    static async edit(name, path, pid, redirect, component, menutype, val, keepalive, aid) {
        return query(`UPDATE access SET name = '${name}', path = '${path??""}', pid = ${pid??0}, redirect = '${redirect??""}', component = '${component??""}', menutype =${menutype}, val = '${val??""}', keepalive =${keepalive??2} WHERE aid = ${aid}`)
    }

    static del(aid) {
        return query(`delete from access where aid=${aid}`)
    }

    static async getRoleAccess(rid) {
        return query(`select aid from roleaccess where rid=${rid}`)
	
    }
	
	static getRouter(rid){
		return query(`select * from access where aid in (select aid from roleaccess where rid=${rid})`)

	}

    static async addRoleAccess(rid, aidArr) {
        // 删除这个角色所有的权限
        await query(`delete from roleaccess where rid=${rid}`)
        for (let i = 0; i < aidArr.length; i++) {
            await query(`INSERT INTO roleaccess(rid, aid) VALUES (${rid}, ${aidArr[i]})`)
        }
        return true
    }
}
module.exports = accessModel
